<template>
  <!-- 数据层级大于二级，判断一级有数据才渲染=》 v-if="detail.categories" -->
  <div class="xtx-goods-page" v-if="detail.categories">
    <div class="container">
      <!-- 面包屑 -->
      <XtxBread separator="/">
        <XtxBreadItem to="/">首页</XtxBreadItem>
        <!-- 一级分类 -->
        <XtxBreadItem to="/">{{ detail.categories[1].name }}</XtxBreadItem>
        <!-- 二级分类 -->
        <XtxBreadItem to="/">{{ detail.categories[0].name }}</XtxBreadItem>
        <!-- 二级分类下的当前商品 -->
        <XtxBreadItem to="/">{{ detail.name }}</XtxBreadItem>
      </XtxBread>
      <!-- 商品信息 -->
      <!-- 商品信息 -->
      <div class="goods-info">
        <!-- 新增结构 -->
        <!-- 图片预览区 -->
        <div class="media">
          <LeftImgs :list="detail.mainPictures" />
          <!-- 商品售卖信息 -->
          <GoodSales />
        </div>
        <!-- 商品信息区 -->
        <div class="spec">
          <!-- 商品基本信息 -->
          <GoodName />
          <!-- sku选择=>商品属性选择 -->
          <GoodsSku :goods="detail" @change="selSku" />
          <!-- 数量选择 -->
          <XtxNumbox v-model="buyNum" :max="detail.inventory" />
          <XtxButton @click="addCart" type="primary" style="margin-top: 20px">
            加入购物车
          </XtxButton>
        </div>
      </div>
      <!-- 商品详情 -->
      <div class="goods-footer">
        <div class="goods-article">
          <!-- 商品+评价 -->
          <div class="goods-tabs">
            <!-- 详情图片列表 -->
            <img
              v-imglazy="url"
              v-for="url in detail.details.pictures"
              :key="url"
            />
          </div>
        </div>
        <!-- 24热榜+专题推荐 -->
        <div class="goods-aside"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, provide } from 'vue'
import { findGoods } from '@/api/goods'
import { useRoute, useRouter } from 'vue-router'
import GoodSales from './components/goods-sales.vue'
import GoodName from './components/goods-name.vue'
import msg from '@/components/Message'
import { useStore } from 'vuex'
// 左侧图片列表
import LeftImgs from './components/goods-image.vue'

const useDetailData = () => {
  const detail = ref({})
  // 在setup第一层注入共享数据
  const buyNum = ref(1)
  provide('detail', detail)
  const route = useRoute()
  const getGoods = async () => {
    const { result } = await findGoods(route.params.id)
    console.log('商品详情', result)
    detail.value = result
  }
  getGoods()
  return { detail, buyNum }
}
const useSkuSel = (detail) => {
  const currSel = ref(null) // 存储当前选中的sku商品信息
  const selSku = (skuInfo) => {
    // 判断是否是有效sku信息（不为空）
    console.log('选中的sku信息：', skuInfo)
    if (skuInfo.skuId) {
      // 显示选择之后的价格并更新库存
      detail.value.price = skuInfo.price
      detail.value.oldPrice = skuInfo.oldPrice
      detail.value.inventory = skuInfo.inventory
      currSel.value = skuInfo
    } else {
      currSel.value = null
    }
  }
  return { selSku, currSel }
}
const useAddCart = (currSel, detail, buyNum) => {
  const store = useStore()
  const router = useRouter()
  // 加入购物车
  const addCart = async () => {
    /**
         * 加入购物车需要满足条件：
         * 1. 选择商品的sku属性=》产生有效的sku商品数据
         * 2. 有效的sku商品数据库存大于0
         */
    if (!currSel.value) {
      return msg({ text: '请选择商品的sku属性！' })
    }
    if (currSel.value.inventory === 0) {
      return msg({ text: '卖完了~' })
    }
    // 执行加入购物车
    // 当前要存入购物车的商品数据
    const currGood = {
      id: detail.value.id,
      name: detail.value.name,
      picture: detail.value.mainPictures[0],
      skuId: currSel.value.skuId, // sku属性ID（唯一）
      price: currSel.value.oldPrice, // 价格
      nowPrice: currSel.value.price,
      attrsText: currSel.value.specsText,
      stock: currSel.value.inventory, // 库存
      selected: true, // 是否在购物车选中
      isEffective: true, // 是否是有效商品
      count: buyNum.value // 购买数量
    }
    console.log('执行加入购物车', currGood)
    // store.dispatch('cart/addCartAction', currGood)
    try {
      const res = await store.dispatch('cart/addCartAction', currGood)
      console.log('加入成功：', res)
      msg({ type: 'success', text: res })
      router.push('/cart')
    } catch (error) {
      console.log('加入失败：', error)
    }
  }
  return { addCart }
}
export default {
  name: 'XtxGoodsPage',
  components: {
    LeftImgs,
    GoodSales,
    GoodName
  },
  setup () {
    const { detail, buyNum } = useDetailData()
    const { selSku, currSel } = useSkuSel(detail)
    const { addCart } = useAddCart(currSel, detail, buyNum)
    return { detail, selSku, buyNum, addCart, currSel }
  }
}
</script>

<style scoped lang='less'>
.goods-info {
  min-height: 600px;
  background: #fff;
  display: flex;
  // 新增样式
  .media {
    width: 580px;
    height: 600px;
    padding: 30px 50px;
  }
  .spec {
    flex: 1;
    padding: 30px 30px 30px 0;
  }
}
.goods-footer {
  display: flex;
  margin-top: 20px;
  .goods-article {
    width: 940px;
    margin-right: 20px;
  }
  .goods-aside {
    width: 280px;
    min-height: 1000px;
    background: #fff;
  }
}
.goods-tabs {
  min-height: 600px;
  background: #fff;
  img {
    width: 100%;
  }
}
.goods-warn {
  min-height: 600px;
  background: #fff;
  margin-top: 20px;
}
</style>
